package com.kele.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;




public class ExcelUtil {

    /**
     * 将file1中的json数据转化为Excel表在file2位置存储
     * @param file1 存有JSON的TXT文档位置
	 * @param file2 输出Excel表的位置
     * @return void
     * @author Kele
     * @date 2021/4/13 17:19
     */
    public static void jsonToExcel(String file1, String file2) {
        StringBuilder sb = new StringBuilder();
        try {
            FileReader in = new FileReader(new File(file1));

            BufferedReader inBR = new BufferedReader(in);
            String stext = null;
            while ((stext = inBR.readLine()) != null) {
                sb.append(stext);
            }
            inBR.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String uploadFile = file2;
            OutputStream fos = new FileOutputStream(uploadFile);
            XSSFWorkbook workBook = new XSSFWorkbook();
            XSSFSheet sheet = workBook.createSheet();

            XSSFRow row = null;
            XSSFCell cell = null;

            row = sheet.createRow(0);
            String[] names = {"序号", "订单号", "记录时间", "CDNIP"};
            for (int index = 0; index < 4; index++) {
                cell = row.createCell(index);
                cell.setCellValue(names[index]);
            }
            int count = 1;

            JSONObject obj = JSONObject.parseObject(sb.toString());
            JSONArray rows = obj.getJSONArray("rows");
            for (Object row1 : rows) {
                JSONObject item = (JSONObject)row1;
                String orderId = item.getString("orderId");
                String createTime = item.getString("createTime");
                String cdnIp = item.getString("cdnIp");

                row = sheet.createRow(count);
                cell = row.createCell(0);
                cell.setCellValue(count);
                cell = row.createCell(1);
                cell.setCellValue(orderId);
                cell = row.createCell(2);
                cell.setCellValue(createTime);
                cell = row.createCell(3);
                cell.setCellValue(cdnIp);
                count++;
            }
            workBook.write(fos);
            System.out.println("输出完成");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("输出失败");
        }
    }

}
